part of _;

extension on HomePage {
  void controller_checkNetLines({bool log = false}) async {
    var resultIndex = 0;
    var resultTime = YConfig.timeOut;
    final ipsStr = await yRead(IFinal.Saves.lines);
    final results = ipsStr!.split(",");
    if (results.length <= 1) return;
    final dio = Dio();
    dio.options.connectTimeout = Duration(milliseconds: YConfig.timeOut);
    dio.options.receiveTimeout = Duration(milliseconds: YConfig.timeOut);
    dio.options.sendTimeout = Duration(milliseconds: YConfig.timeOut);
    String linesResult = "";
    for (var i = 0; i < results.length; i++) {
      final ip = results[i];
      try {
        var startTime = DateTime.now().millisecondsSinceEpoch;
        var response = await dio.post(ip + IFinal.Urls.interface, data: {"jkid": IFinal.Jkids.checkLine});
        var endTime = DateTime.now().millisecondsSinceEpoch;
        if (response.statusCode == 200) {
          if (response.data["root"]["code"] == "1") {
            if (endTime - startTime < resultTime) {
              resultTime = endTime - startTime;
              linesResult += "线路${i + 1}，地址：$ip，心跳耗时：$resultTime，比较结果：faster\n";
              resultIndex = i;
            } else {
              linesResult += "线路${i + 1}，地址：$ip，心跳耗时：${endTime - startTime}，比较结果：slower\n";
            }
          }
        }
      } catch (e) {
        linesResult += "线路${i + 1}，地址：$ip，心跳错误：${e.toString()}\n";
      }
    }
    linesResult += "本轮扫描时间：${DateTime.now()}，最优结果：线路${resultIndex + 1}\n";
    ySave(IFinal.Saves.linesResult, linesResult);
    if (log) yLog(linesResult);
    ySave(IFinal.Saves.linesIndex, resultIndex.toString());
    IFinal.Others.BaseIP = (resultIndex + 1 > IFinal.Configs_Server.lines.length) ? IFinal.Configs_Server.lines.first : IFinal.Configs_Server.lines[resultIndex];
    yConfigIP(IFinal.Others.BaseIP + IFinal.Urls.interface);
    yConfigUpdateIP(YConfig.IP);
    yRun(() => controller_checkNetLines(), delay: 60000);
  }

  void controller_loginYIM() async {
    YIM.userManager.logout();
    final userModel = await AppUtils.readUserModel();
    if (userModel == null) return;
    YIM.userManager.login(
      user: userModel.yim_user,
      token: userModel.yim_token,
      callback: (result) {
        if (result.code != YIMEnum_LoginResult.Success) {
          yRun(() => controller_loginYIM(), delay: 2000);
          return;
        }
        controller_conversation!.queryRecentConversations();
      },
    );
    YIM.listenerManager.register_status_online(callback: (result) {
      switch (result.code) {
        case YIMEnum_OnlineState.Reconnecting:
          controller_conversation!.queryRecentConversations();
          break;
        case YIMEnum_OnlineState.Reconnected:
          controller_conversation!.queryRecentConversations();
          break;
        case YIMEnum_OnlineState.Kick:
          yShowBuilder("您的账号在其他设备登录", () {
            AppUtils.reLaunchApp(goLogin: true);
          }, null, false, posTitle: "重新登录");
          break;
      }
    });
    YIM.listenerManager.register_recentConversation(callback: () {
      controller_conversation!.queryRecentConversations();
    });
    YIM.listenerManager.register_revoke(callback: (message) {
      final conversation = controller_conversation!.getSelectConversation();
      if (conversation != null && conversation.conversationID == message.conversationID) {
        controller_chat!.onRecRevoke(message);
      }
    });
    YIM.listenerManager.register_status_msg_receipt(callback: (conversationID) {
      final conversation = controller_conversation!.getSelectConversation();
      if (conversation != null && conversation.conversationID == conversationID) {
        controller_chat!.onRecReceipt(conversationID);
      }
    });
    YIM.listenerManager.register_message(callback: (messages) {
      controller_conversation!.clearUnReadCount();
      MessageUtils.onRecMessage(messages: messages);
      final conversation = controller_conversation!.getSelectConversation();
      if (conversation != null) {
        controller_chat!.onRecMessage(messages.where((message) => message.from == conversation.conversationID).toList());
      }
    });
  }
}
